package org.leo.flow.flow;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.leo.flow.bean.InData;
import org.leo.flow.bean.OutData;
import org.leo.flow.plugin.FlowPlugin;
import org.leo.flow.step.IStep;
import org.leo.flow.step.StepHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Created on 2017年2月4日
 * <p>
 * Description 默认流程类
 * <p>
 * Copyright xxx (c) 2019 .
 * 
 * @author leo
 */
public class DefaultFlow implements IFlow {

	/**
	 * 流程ID
	 */
	private String id;

	/**
	 * 流程名称
	 */
	private String name;

	private Map<String, Object> param;

	private Logger log = LoggerFactory.getLogger(this.getClass());

	OutData<String, Object> out = null;

	/**
	 * 插件
	 */
	private List<FlowPlugin> plugins = new ArrayList<FlowPlugin>();

	/**
	 * 
	 * Created on 2017年3月7日 .
	 * <p>
	 * Description 添加插件
	 *
	 * @author leo
	 * @param plugin
	 *            void
	 */
	public void addPlugin(FlowPlugin plugin) {
		plugin.setFlow(this);
		plugins.add(plugin);
	}

	private long startTime;

	/**
	 * Created on 2017年2月4日 .
	 * <p>
	 * Description 获取结果方法
	 * 
	 * @author leo
	 * @return SOut
	 */
	@Override
	public OutData<String, Object> getResult() {
		long interval = System.currentTimeMillis() - startTime;
		log.info("流程--" + this.getName() + "执行结束... 花费" + interval + "ms");
		return out;
	}

	/**
	 * Created on 2017年2月4日 .
	 * <p>
	 * Description 运行方法
	 * 
	 * @author leo
	 * @param step
	 * @param data
	 * @return void
	 * @throws Exception 
	 * @throws BussinessException
	 */
	@Override
	public void run(IStep step, InData<String, Object> data) throws Exception {
			startTime = System.currentTimeMillis();
			log.info("流程--" + this.getName() + "执行开始...");

			// 将流程注入到步骤中
			step.setFlow(this);

			StepHandler stepHandler = new StepHandler();
			stepHandler.setStep(step);
			out = stepHandler.handleStep(data);
	}

	/**
	 * 
	 * Created on 2017年3月27日 .
	 * <p>
	 * Description 执行插件集合
	 *
	 * @author leo void
	 */
	@Override
	public void runPlugin() {
		// 插件执行
		for (FlowPlugin plugin : plugins) {
			plugin.handle();
		}
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		if (name == null) {
			name = this.toString();
		}
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Map<String, Object> getParam() {
		return param;
	}

	@Override
	public void setParam(Map<String, Object> param) {
		this.param = param;
	}

}
